package me.minecraft.plugin.itemsave.command;

import me.minecraft.plugin.itemsave.ItemSave;
import me.minecraft.plugin.itemsave.config.MessageConfig;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
import org.jetbrains.annotations.NotNull;

import java.util.*;

/**
 * @author langle__
 * @version 1.0
 */
public class MainCommand implements TabExecutor {

    private final Map<String, SubCommand> map = new HashMap<>();

    public MainCommand() {
        this.registerSubCommand("give", new GiveCommand());
        this.registerSubCommand("save", new SaveCommand());
        this.registerSubCommand("delete", new DeleteCommand());
        this.registerSubCommand("reload", new ReloadCommand());
        this.registerSubCommand("list", new ListCommand());
        this.registerSubCommand("help", new HelpCommand());
    }

    public void onCommand(CommandSender sender) {
        sender.sendMessage("§6ItemSave §7[§f" + ItemSave.instance.getDescription().getVersion() + "§7]");
        sender.sendMessage("§7作者: §f[langle__]");
        sender.sendMessage("§7命令: §f/is help");
    }

    @Override
    public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {
        if (args.length == 0) {
            onCommand(sender);
            return true;
        }
        SubCommand subCommand = map.get(args[0]);
        if (subCommand == null) return true;
        boolean permission = subCommand.hasPermission(sender);
        if (!permission) {
            sender.sendMessage(MessageConfig.INSTANCE.getCommonNoPermission());
            return true;
        }
        String[] array = Arrays.copyOfRange(args, 1, args.length);
        subCommand.onCommand(sender, array);
        return true;
    }

    @Override
    public List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, @NotNull String[] args) {
        if (args.length == 1) return new ArrayList<>(map.keySet());
        SubCommand subCommand = map.get(args[0]);
        if (subCommand == null) return Collections.emptyList();
        String[] array = Arrays.copyOfRange(args, 1, args.length);
        return subCommand.onTabComplete(sender, array);
    }

    public void registerSubCommand(String name, SubCommand subCommand) {
        map.put(name, subCommand);
    }

}
